/**
 * 分类页面脚本
 */

// 全局变量
let currentPage = 1
let hasMore = true
let isLoading = false
let categoryId = 0
let categoryType = ""
let activeFilters = {}
let currentSort = "date"
let currentOrder = "desc"
let categorized = loadCategorized()
const urlParams = new URLSearchParams(window.location.search)
categoryType = urlParams.get("type") || "movie"
let categoriesThis = categorized.find((cat) => cat.type === categoryType)


// 如果是全局对象，则可以简单声明
const AppConfig = window.AppConfig || {}
const API = window.API || {}
const UI = window.UI || {}

document.addEventListener("DOMContentLoaded", () => {
  // 遍历查找categorized下type=categoryType的分类，获取其subcategories后将subcategories下的子元素中id jion,
  categoryId = categoriesThis.subcategories.map((subcategory) => subcategory.id).join(",")

  // 设置导航高亮
  setActiveNavItem()

  // 初始化筛选面板
  initFilterPanel()

  // 初始化排序
  initSorting()

  // 加载媒体列表
  loadMediaList()

  // 初始化无限滚动
  initInfiniteScroll()

  // 滚动条到底部100px时触发 loadingMore 显示（带防抖）
  setupScrollToShowLoadingMore()
  
  // 手动初始化下拉菜单
  initCategoryDropdowns()
})

/**
 * 设置导航高亮
 */
function setActiveNavItem() {
  // 移除所有高亮
  document.querySelectorAll(".nav-item").forEach((item) => {
    item.classList.remove("active")
  })

  // 设置当前分类高亮
  const navItem = document.getElementById(`nav-${categoryType}`)
  if (navItem) {
    navItem.classList.add("active")
  }
}

/**
 * 初始化筛选面板
 */
async function initFilterPanel() {
  const filterToggle = document.getElementById("filterToggle")
  const filterPanel = document.getElementById("filterPanel")
  const collapseFilters = document.getElementById("collapseFilters")
  const filterGroups = document.getElementById("filterGroups")
  const clearFilters = document.getElementById("clearFilters")

  // 监听筛选按钮点击
  filterToggle?.addEventListener("click", () => {   
    filterPanel.classList.toggle("open") 
    if (filterPanel.classList.contains("open")) {
      filterPanel.style.display = "block"
    }else{
      setTimeout(() => {
        filterPanel.style.display = "none"
      }, 250);
    }    
  })
  document.addEventListener("click", (event) => {
    if (!filterToggle.contains(event.target)) {
      filterPanel.classList.remove("open")
      setTimeout(() => {
        filterPanel.style.display = "none"
      }, 250)
    }
  })
  // 监听收起筛选按钮点击
  collapseFilters?.addEventListener("click", () => {    
    filterPanel.classList.remove("open")
    setTimeout(() => {
      filterPanel.style.display = "none"
    }, 250)
  })

  // 监听清除筛选按钮点击
  clearFilters?.addEventListener("click", () => {
    activeFilters = {}
    updateFilterUI()
    loadMediaList(true)
  })

  try {
    // 获取分类
    const activeSource = AppConfig.getActiveSource()
    if (!activeSource) return

    const categories = await API.getCategories(activeSource)

    // 构建筛选选项
    const filterOptions = [
      {
        id: "t",
        name: "分类",
        options: categoriesThis.subcategories.map((cat) => ({ value: cat.id.toString(), label: cat.name })),
      },
      {
        id: "year",
        name: "发行年份",
        options: [
          { value: "2024", label: "2024" },
          { value: "2023", label: "2023" },
          { value: "2022", label: "2022" },
          { value: "2021", label: "2021" },
          { value: "2020", label: "2020" },
          { value: "2019", label: "2019" },
          { value: "2018", label: "2018" },
          { value: "2017", label: "2017" },
          { value: "2016", label: "2016" },
          { value: "2015", label: "2015" },
        ],
      },
      {
        id: "area",
        name: "国家和地区",
        options: [
          { value: "大陆", label: "中国大陆" },
          { value: "中国香港", label: "中国香港" },
          { value: "中国台湾", label: "中国台湾" },
          { value: "美国", label: "美国" },
          { value: "韩国", label: "韩国" },
          { value: "日本", label: "日本" },
          { value: "泰国", label: "泰国" },
          { value: "英国", label: "英国" },
          { value: "法国", label: "法国" },
          { value: "德国", label: "德国" },
        ],
      },      
      {
        id: "status",
        name: "状态",
        options: [
          { value: "all", label: "全部" },
          { value: "completed", label: "已完结" },
          { value: "ongoing", label: "连载中" },
          { value: "upcoming", label: "即将上映" },
        ],
      },
    ]

    filterGroups.innerHTML = ""

    filterOptions.forEach((filter) => {
      // 跳过没有选项的筛选组
      if (filter.options.length === 0) return

      const filterGroup = document.createElement("div")
      filterGroup.className = "filter-group"
      filterGroup.innerHTML = `
        <div class="filter-group-header">
          <h4 class="filter-group-title">${filter.name} <i class="ri-arrow-right-s-line"></i></h4>
          ${
            activeFilters[filter.id]
              ? `
          <button class="btn-icon clear-filter" data-id="${filter.id}">
            <i class="ri-close-line"></i>
          </button>
          `
              : ""
          }
        </div>
        <div class="filter-options" id="filter-${filter.id}"></div>
      `

      filterGroups.appendChild(filterGroup)

      // 渲染筛选选项
      const optionsContainer = filterGroup.querySelector(`#filter-${filter.id}`)

      filter.options.forEach((option) => {
        const isActive = activeFilters[filter.id] === option.value

        const optionButton = document.createElement("button")
        optionButton.className = `btn btn-sm ${isActive ? "btn-primary" : "btn-outline"}`
        optionButton.textContent = option.label
        optionButton.dataset.value = option.value
        optionButton.dataset.filterId = filter.id

        optionButton.addEventListener("click", () => {
          // 切换筛选状态
          if (isActive) {
            delete activeFilters[filter.id]
          } else {
            activeFilters[filter.id] = option.value
          }
          console.log(activeFilters)
          updateFilterUI()
          loadMediaList(true)
        })

        optionsContainer.appendChild(optionButton)
      })
    })

    // 添加清除筛选按钮事件
    document.querySelectorAll(".clear-filter").forEach((btn) => {
      btn.addEventListener("click", (e) => {
        e.stopPropagation()
        const filterId = btn.dataset.id

        delete activeFilters[filterId]
        updateFilterUI()
        loadMediaList(true)
      })
    })
  } catch (error) {
    console.error("初始化筛选面板失败:", error)
  }
}

/**
 * 更新筛选UI
 */
function updateFilterUI() {
  // 更新筛选徽章
  const filterBadge = document.getElementById("filterBadge")
  const filterCount = Object.keys(activeFilters).length

  if (filterBadge) {
    filterBadge.textContent = filterCount
    filterBadge.style.display = filterCount > 0 ? "inline-flex" : "none"
  }

  // 更新清除筛选按钮
  const clearFilters = document.getElementById("clearFilters")
  if (clearFilters) {
    clearFilters.style.display = filterCount > 0 ? "flex" : "none"
  }

  // 更新筛选选项的激活状态
  document.querySelectorAll(".filter-options button").forEach((button) => {
    const filterId = button.dataset.filterId
    const filterValue = button.dataset.value
    
    if (activeFilters[filterId] === filterValue) {
      button.classList.add("btn-primary")
      button.classList.remove("btn-outline")
    } else {
      button.classList.remove("btn-primary")
      button.classList.add("btn-outline")
    }
  })
  
  // 更新筛选组标题的激活状态
  document.querySelectorAll(".filter-group").forEach((group) => {
    const title = group.querySelector(".filter-group-title")
    const filterId = group.querySelector(".filter-options button")?.dataset.filterId
    
    if (title && filterId && activeFilters[filterId]) {
      title.classList.add("active")
    } else if (title) {
      title.classList.remove("active")
    }
  })
}

/**
 * 初始化排序
 */
function initSorting() {
  const sortItems = document.querySelectorAll("[data-sort]")
  const orderItems = document.querySelectorAll("[data-order]")
  const sortLabel = document.getElementById("sortLabel")
  const orderLabel = document.getElementById("orderLabel")

  // 监听排序选项点击
  sortItems.forEach((item) => {
    item.addEventListener("click", () => {
      const sort = item.dataset.sort
      currentSort = sort

      // 更新排序标签
      if (sortLabel) {
        sortLabel.textContent = getSortLabel(sort)
      }

      // 重新加载列表
      loadMediaList(true)
    })
  })

  // 监听排序顺序点击
  orderItems.forEach((item) => {
    item.addEventListener("click", () => {
      const order = item.dataset.order
      currentOrder = order

      // 更新排序顺序标签
      if (orderLabel) {
        orderLabel.textContent = order === "asc" ? "升序" : "降序"
      }

      // 更新排序顺序图标
      const orderIcon = document.querySelector("#orderDropdown .dropdown-toggle i:first-child")
      if (orderIcon) {
        orderIcon.className = order === "asc" ? "ri-sort-asc" : "ri-sort-desc"
      }

      // 重新加载列表
      loadMediaList(true)
    })
  })
}

/**
 * 获取排序标签
 * @param {string} sort 排序类型
 * @returns {string} 排序标签
 */
function getSortLabel(sort) {
  switch (sort) {
    case "date":
      return "添加日期"
    case "title":
      return "标题"
    case "rating":
      return "评分"
    case "year":
      return "发行年份"
    default:
      return "添加日期"
  }
}

/**
 * 加载媒体列表
 * @param {boolean} reset 是否重置
 */
async function loadMediaList(reset = false) {
  const mediaGrid = document.getElementById("mediaGrid")
  const loadingMore = document.getElementById("loadingMore")
  const totalItems = document.getElementById("totalItems")

  // 调试信息
  console.debug("[loadMediaList] called", {reset, currentPage, hasMore, isLoading})
  if (!mediaGrid) {
    console.warn("[loadMediaList] mediaGrid not found")
    return
  }

  // 重置列表
  if (reset) {
    console.debug("[loadMediaList] reset triggered")
    mediaGrid.innerHTML = `
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
    `
    currentPage = 1
    hasMore = true
  }

  if (isLoading || !hasMore) {
    console.debug("[loadMediaList] Blocked: isLoading or !hasMore", {isLoading, hasMore})
    return
  }

  isLoading = true
  if (loadingMore) loadingMore.style.display = "flex"

  try {
    const activeSource = AppConfig.getActiveSource()
    console.debug("[loadMediaList] activeSource", activeSource)
    if (!activeSource) {
      mediaGrid.innerHTML = `
        <div class="empty-state">
          <i class="ri-film-line"></i>
          <p>请先添加媒体源</p>
        </div>
      `
      isLoading = false
      if (loadingMore) loadingMore.style.display = "none"
      return
    }
    // 构建查询参数
    const params = {
      page: currentPage,
      t: activeFilters.t? activeFilters.t : categoryId,
      by: currentSort,
      order: currentOrder,
      ...activeFilters,
    }

    // 获取媒体列表
    const response = await API.getMediaList(activeSource, params.page, params.category, '', params)
    // 更新总数
    if (totalItems) {
      totalItems.textContent = `共 ${response.total} 个项目 ${response.page} 页 `
      // 更新缓存
      window.AppConfig.updateNestedConfig("cache.total.${categoryType}", response.total)
    }

    // 清空加载中状态
    if (reset) {
      mediaGrid.innerHTML = ""
    }

    if (response.list.length === 0 && currentPage === 1) {
      mediaGrid.innerHTML = `
        <div class="empty-state">
          <i class="ri-film-line"></i>
          <p>暂无内容</p>
        </div>
      `
      hasMore = false
      isLoading = false
      if (loadingMore) loadingMore.style.display = "none"
      return
    }

    // 添加媒体卡片
    response.list.forEach((item) => {
      const card = UI.createMediaCard(item)
      mediaGrid.appendChild(card)
    })
    removeListLoading()
    // 更新分页状态
    hasMore = response.page < response.pagecount
    currentPage++
  } catch (error) {
    console.error("加载媒体列表失败:", error)
    if (currentPage === 1) {
      mediaGrid.innerHTML = `
        <div class="error-state">
          <i class="ri-error-warning-line"></i>
          <p>加载失败，请重试</p>
        </div>
      `
    }
  } finally {
    isLoading = false
    if (loadingMore) loadingMore.style.display = "none"
  }
}

/**
 * 初始化无限滚动
 */
function initInfiniteScroll() {
  const mediaGrid = document.getElementById("mediaGrid")
  const loadingMore = document.getElementById("loadingMore")

  if (!mediaGrid || !loadingMore) return

  // 兼容：如果首次进入页面 loadingMore 是隐藏的，先显示再隐藏，保证 observer 能监听到
  loadingMore.style.display = "block"
  setTimeout(() => {
    loadingMore.style.display = "none"
  }, 0)

  // 创建交叉观察器
  const observer = new IntersectionObserver(
    (entries) => {
      if (entries[0].isIntersecting && !isLoading && hasMore) {
        loadMediaList()
      }
    },
    { threshold: 0.1 },
  )

  // 观察加载更多元素
  observer.observe(loadingMore)
}

/**
 * 滚动条到底部100px时触发 loadingMore 显示（带防抖）
 */
function setupScrollToShowLoadingMore() {
  let debounceTimer = null
  const mediaGrid = document.getElementById("mediaGrid")
  mediaGrid.addEventListener('scroll', function() {
    if (debounceTimer) clearTimeout(debounceTimer)
    debounceTimer = setTimeout(() => {
      const scrollTop = mediaGrid.scrollTop
      const windowHeight = mediaGrid.clientHeight
      const docHeight = mediaGrid.scrollHeight
      // 距离底部100px以内
      if (docHeight - (scrollTop + windowHeight) <= 50) {
        const loadingMore = document.getElementById('loadingMore')
        if (loadingMore) loadingMore.style.display = 'flex'
      }
    }, 100)
  })
}

/**
 * 初始化分类页面下拉菜单
 */
function initCategoryDropdowns() {
  const sortDropdown = document.getElementById("sortDropdown")
  const orderDropdown = document.getElementById("orderDropdown")
  
  sortDropdown.addEventListener("click", () => {
    orderDropdown.classList.toggle("open")
  })
  orderDropdown.addEventListener("click", () => {
    orderDropdown.classList.toggle("open")
  })
  
  document.addEventListener("click", () => {
    sortDropdown.classList.remove("open")
    orderDropdown.classList.remove("open")
  })
}
